﻿using UnityEngine;
using System.Collections;

public class characterController : MonoBehaviour {

	bool facingRight = true;
	public bool grounded = false;
	public float maxSpeed = 5f;
	public float jumpForce = 700f;

	public LayerMask whatIsGround;
	public Transform groundCheck;
	float groundRadius = .2f;

	Animator anim;

	// Use this for initialization
	void Start () {
		anim=GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		float move = Input.GetAxis("Horizontal");

		rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);

		grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
		anim.SetBool("Grounded", grounded);

		anim.SetFloat("Speed", Mathf.Abs(move));
		anim.SetFloat("vSpeed", rigidbody2D.velocity.y);

		if(move > 0 && !facingRight)
			flipCharacter();
		else if(move < 0 && facingRight)
			flipCharacter();
	}

	void Update(){
		if(grounded && Input.GetKeyDown(KeyCode.Space)){
			rigidbody2D.AddForce(new Vector2(0f, jumpForce));
			anim.SetBool("Grounded", false);
		}
	}

	void flipCharacter(){
		facingRight = !facingRight;
		transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
	}
	
}
